package org.ushio.speech_module.speech.sentence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.ushio.common_module.config.annotation.Loggable;
import org.ushio.common_module.debounce.Debounce;
import org.ushio.common_module.util.response.ResponseResult;
import org.ushio.common_module.util.response.ResultCode;

import java.io.IOException;
import java.util.List;

/**
 * @author 陈红
 */
@RestController
@RequestMapping("/api/sentences")
public class SentencesController {

    @Autowired
    private SentenceService sentenceService;

    @Autowired
    @Qualifier("speechRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    private static final String CACHE_KEY_PREFIX = "sentence:";
    private static final String CHAPTER_CACHE_KEY_PREFIX = "chapter_sentences:";

    /**
     * 获取指定 ID 的句子
     * @param id 句子 ID
     * @return 句子对象
     */
    @GetMapping("/{id}")
    public ResponseResult<Sentence> getSentenceById(@PathVariable Long id) {
        String key = CACHE_KEY_PREFIX + id;
        Sentence sentence = (Sentence) redisTemplate.opsForValue().get(key);

        if (sentence == null) {
            sentence = sentenceService.findById(id);
            if (sentence != null) {
                redisTemplate.opsForValue().set(key, sentence);
            } else {
                return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "句子不存在");
            }
        }
        return ResponseResult.success(sentence);
    }

    /**
     * 根据章节 ID 获取所有句子
     * @param chapterId 章节 ID
     * @return 句子列表
     */
    @GetMapping("/chapter/{chapterId}")
    public ResponseResult<List<Sentence>> getSentencesByChapterId(@PathVariable Long chapterId) {
        String key = CHAPTER_CACHE_KEY_PREFIX + chapterId;
        List<Sentence> sentences = (List<Sentence>) redisTemplate.opsForValue().get(key);

        if (sentences == null) {
            sentences = sentenceService.findByChapterId(chapterId);
            if (sentences != null && !sentences.isEmpty()) {
                redisTemplate.opsForValue().set(key, sentences);
            } else {
                return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "未找到该章节的句子");
            }
        }
        return ResponseResult.success(sentences);
    }

    /**
     * 创建句子
     * @param chapterId 章节 ID
     * @param englishText 英文文本
     * @param chineseText 中文文本
     * @param audioFile 音频文件
     * @return 句子 ID
     */
    @PostMapping("/upload")
    @Debounce(interval = 500)
    @Loggable("增加句子")
    public ResponseResult<Integer> createSentenceWithFile(
            @RequestParam("chapterId") Long chapterId,
            @RequestParam("englishText") String englishText,
            @RequestParam("chineseText") String chineseText,
            @RequestParam("audio") MultipartFile audioFile) {

        // 创建新的句子对象并设置相关字段
        Sentence sentence = new Sentence();
        sentence.setChapterId(chapterId);
        sentence.setEnglishText(englishText);
        sentence.setChineseText(chineseText);

        try {
            // 调用服务层方法，处理文件并存储到数据库
            int result = sentenceService.insertSentence(sentence, audioFile);
            if (result > 0) {
                // 更新单个句子的缓存
                String sentenceKey = CACHE_KEY_PREFIX + sentence.getSentenceId();
                redisTemplate.opsForValue().set(sentenceKey, sentence);

                // 清除章节缓存，强制重新加载章节下的所有句子
                String chapterKey = CHAPTER_CACHE_KEY_PREFIX + chapterId;
                redisTemplate.delete(chapterKey);

                return ResponseResult.success(result);
            } else {
                return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "创建句子失败");
            }
        } catch (IOException e) {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "音频文件处理失败");
        }
    }

    /**
     * 更新句子和音频文件
     * @param sentenceId 句子 ID
     * @param chapterId 章节 ID
     * @param englishText 英文文本
     * @param chineseText 中文文本
     * @param audioFile 音频文件
     * @return 更新结果
     */
    @PutMapping("/{sentenceId}/upload")
    @Debounce(interval = 500)
    @Loggable("更新句子")
    public ResponseResult<Integer> updateSentenceWithFile(
            @PathVariable("sentenceId") Long sentenceId,
            @RequestParam("chapterId") Long chapterId,
            @RequestParam("englishText") String englishText,
            @RequestParam("chineseText") String chineseText,
            @RequestParam(value = "audio", required = false) MultipartFile audioFile) {

        // 查找要更新的句子
        Sentence sentence = sentenceService.findById(sentenceId);
        if (sentence == null) {
            return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "句子不存在");
        }

        // 更新句子的文本字段
        sentence.setChapterId(chapterId);
        sentence.setEnglishText(englishText);
        sentence.setChineseText(chineseText);

        try {
            // 调用服务层方法更新句子，若有音频文件则更新
            int result = sentenceService.updateSentence(sentence, audioFile);
            if (result > 0) {
                // 更新句子的缓存
                String sentenceKey = CACHE_KEY_PREFIX + sentence.getSentenceId();
                redisTemplate.opsForValue().set(sentenceKey, sentence);

                // 清除章节缓存，强制重新加载该章节下的所有句子
                String chapterKey = CHAPTER_CACHE_KEY_PREFIX + chapterId;
                redisTemplate.delete(chapterKey);

                // 返回更新成功
                return ResponseResult.success(result);
            } else {
                return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "更新句子失败");
            }
        } catch (IOException e) {
            return ResponseResult.failed(ResultCode.INTERNAL_ERROR.getCode(), "音频文件处理失败");
        }
    }

    /**
     * 删除句子
     * @param id 句子 ID
     * @return 删除结果
     */
    @Loggable("删除句子")
    @DeleteMapping("/{id}")
    @Debounce(interval = 500)
    public ResponseResult<Integer> deleteSentence(@PathVariable Long id) {
        // 查找该句子所属的章节ID
        Sentence sentence = sentenceService.findById(id);
        if (sentence == null) {
            return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "句子不存在");
        }
        Long chapterId = sentence.getChapterId();

        // 删除句子数据
        int result = sentenceService.deleteById(id);
        if (result > 0) {
            // 删除该句子的缓存
            String sentenceKey = CACHE_KEY_PREFIX + id;
            redisTemplate.delete(sentenceKey);

            // 清除章节缓存，强制重新加载该章节下的所有句子
            String chapterKey = CHAPTER_CACHE_KEY_PREFIX + chapterId;
            redisTemplate.delete(chapterKey);

            // 返回删除成功
            return ResponseResult.success(result);
        } else {
            return ResponseResult.failed(ResultCode.NOT_FOUND.getCode(), "删除句子失败");
        }
    }

}
